package com.hjs.servlet.dailyinspection.dailyinspectionplan;

import com.hjs.bean.DailyInspectRecording;
import com.hjs.bean.DailyInspectionRecordingComView;
import com.hjs.mapper.DailyInspectRecordingMapper;
import com.hjs.mapper.DailyInspectionRecordingComViewMapper;
import com.hjs.mapper.RoadAuditMapper;
import com.hjs.mapper.RoadMapper;
import com.hjs.tools.Mapper;
import com.hjs.tools.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * @author violetfreesia
 * @date 2020/06/21
 */
@Slf4j
@WebServlet("/getDailyInspectionPlan")
public class GetDailyInspectionPlan extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        RequestUtil requestUtil = new RequestUtil(request, response);
        try (SqlSession sqlSession = Mapper.getSqlSession(true)) {
            DailyInspectionRecordingComViewMapper mapper = sqlSession.getMapper(DailyInspectionRecordingComViewMapper.class);
            List<DailyInspectionRecordingComView> allDailyInspectionRecordingComView;
            //更新巡检计划
            updateDailyInspectionPlan(requestUtil, sqlSession);
            //根据是否传来departmentID决定查询所有还是部门
            if (requestUtil.getString("departmentID") == null) {
                allDailyInspectionRecordingComView = mapper.getAllDailyInspectionRecordingComView();
            } else {
                allDailyInspectionRecordingComView = mapper.getDailyInspectionRecordingComViewByDepartmentId(requestUtil.getInt("departmentID"));
            }
            //返回查询结果
            requestUtil.responseWrite(Mapper.toJsonString(allDailyInspectionRecordingComView));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
            requestUtil.responseFail("查询失败,未知错误");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    }

    /**
     * 跟新巡检计划表
     *
     * @param requestUtil requestUtil
     * @param sqlSession  sqlSession
     */
    private void updateDailyInspectionPlan(RequestUtil requestUtil, SqlSession sqlSession) {
        RoadAuditMapper mapper = sqlSession.getMapper(RoadAuditMapper.class);
        List<Integer> allRoadId;
        if (requestUtil.getString("departmentID") == null) {
            //没传departmentID就去获取所有正在养护的道路id
            allRoadId = mapper.getAllRoadId();
        } else {
            //传了departmentID就去获取这个部门管理的所有道路id
            allRoadId = mapper.getAllRoadIdByDepartmentId(requestUtil.getInt("departmentID"));
        }
        //遍历道路id
        allRoadId.forEach((roadId) -> {
            RoadMapper mapper2 = sqlSession.getMapper(RoadMapper.class);
            //根据道路id获取车行道id
            Integer roadwayId = mapper2.getRoadwayIdByRoadId(roadId);
            LocalDate lastDailyInspectionDate = getLastDailyInspectionDate(roadwayId, sqlSession);
            DailyInspectRecording dailyInspectRecording = new DailyInspectRecording();
            dailyInspectRecording.setRoadwayID(roadwayId);
            dailyInspectRecording.setDailyInspecteDate(LocalDateTime.now());
            DailyInspectRecordingMapper mapper1 = sqlSession.getMapper(DailyInspectRecordingMapper.class);
            if (lastDailyInspectionDate == null) {
//                获取到的最近巡检时间为空这表示没开始巡检 ,则直接插入一条巡检计划
                boolean sqlResult = mapper1.addOneDailyInspectRecording(dailyInspectRecording);
                Mapper.SessionEnd(sqlResult, sqlSession);
            } else {
                //获取道路养护等级
                int maintenanceLevel = getMaintenanceLevelIdByRoadId(roadId, sqlSession);
                //如果现在与上一次时间差超过养护等级的天数,则新增一条巡检计划, 如果不超过就不会更新计划
                if (ChronoUnit.DAYS.between(lastDailyInspectionDate, LocalDate.now()) >= maintenanceLevel) {
                    boolean sqlResult = mapper1.addOneDailyInspectRecording(dailyInspectRecording);
                    Mapper.SessionEnd(sqlResult, sqlSession);
                }
            }
        });
    }

    /**
     * 根据车行道ID获取最近一次日常巡检的日期,若未开始巡检, 则返回空
     *
     * @param roadwayId  车行道ID
     * @param sqlSession sqlSession
     * @return 有就返回最新的巡检时间, 没有就返回空
     */
    private LocalDate getLastDailyInspectionDate(int roadwayId, SqlSession sqlSession) {
        DailyInspectRecordingMapper mapper = sqlSession.getMapper(DailyInspectRecordingMapper.class);
        List<DailyInspectRecording> dailyInspectRecordings = mapper.getDailyInspectRecordingByRoadwayId(roadwayId);
        if (dailyInspectRecordings.size() == 0) {
            return null;
        }
        return dailyInspectRecordings.get(dailyInspectRecordings.size() - 1).getDailyInspecteDate().toLocalDate();
    }

    /**
     * 根据道路id获取养护等级
     *
     * @param roadId     roadId
     * @param sqlSession sqlSession
     * @return 返回养护等级
     */
    private int getMaintenanceLevelIdByRoadId(int roadId, SqlSession sqlSession) {
        RoadMapper mapper = sqlSession.getMapper(RoadMapper.class);
        return mapper.getMaintenanceLevelByRoadId(roadId);
    }

}
